/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_zml.htm
 *
 * Zhiqim Zml is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.zml.expression.primitive;

import org.zhiqim.kernel.util.Asserts;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.zml.ZmlVariable;
import org.zhiqim.zml.exception.ExpressionException;
import org.zhiqim.zml.expression.Primitive;

/**
 * 字符原型，格式为用单引号之内的一个字母或符号，如'a','$'
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class _Char extends Primitive
{
    private final char value;
    
    public _Char(String value) 
    {
        Asserts.as(Validates.isLen(value, 3, 4)?null:"字符["+value+"]格式不对");
        Asserts.as(value.startsWith("'")?null:"字符["+value+"]格式不对");
        Asserts.as(value.endsWith("'")?null:"字符["+value+"]格式不对");
            
        value = value.substring(1, value.length()-1);
        if (value.length() == 1)
        {
            this.value = value.charAt(0);
            return;
        }
        
        //长度==2时，第一个字符必须是转义字符
        Asserts.as(value.length() == 2?null:"字符["+value+"]格式不对");
        Asserts.as('\\' == value.charAt(0)?null:"字符["+value+"]格式不对");
        
        char tc = value.charAt(1);
        switch (tc)
        {
        case '\\':this.value = '\\';;break;
        case '\"':this.value = '\"';break;
        case '\'':this.value = '\'';break;
        case 'b':this.value = '\b';break;
        case 'f':this.value = '\f';break;
        case 'n':this.value = '\n';break;
        case 'r':this.value = '\r';break;
        case 't':this.value = '\t';break;
        default:throw Asserts.exception("字符["+value+"]格式不对");
        }
    }
    
    @Override
    public int getType()
    {
        return CHAR;
    }
    
    @Override
    public Object build(ZmlVariable variableMap) throws ExpressionException
    {
        return value;
    }
    
    @Override
    public String toString()
    {
        return String.valueOf(value);
    }
    
    public char getValue()
    {
        return value;
    }
}
